import 'dart:io';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:logger/logger.dart';
import 'dart:ui';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);
  var ss = window.defaultRouteName;

  String _getPageName(String s) {
    if (s.indexOf("?") == -1) {
      return s;
    } else {
      return s.substring(0, s.indexOf("?"));
    }
  }

  String _getPageParamJsonStr(String s) {
    if (s.indexOf("?") == -1) {
      return "{}";
    } else {
      return s.substring(s.indexOf("?") + 1);
    }
  }

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or press Run > Flutter Hot Reload in a Flutter IDE). Notice that the
        // counter didn't reset back to zero; the application is not restarted.
        primarySwatch: Colors.blue,
      ),
      routes: {
        '/two_page': (context) {
          return TwoPage();
        },
        '/one_page': (context) {
          return OnePage();
        },
      },
      home: _widgetForRoute(_getPageName(ss), _getPageParamJsonStr(ss)),
    );
  }
}

Widget _widgetForRoute(String s, String json) {
  switch (s) {
    case "OnePage":
      return new OnePage();
    case "MyHomePage":
      return new MyHomePage(params:json);
    case "TwoPage":
      return new TwoPage();
  }
  return MyHomePage();
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, this.params}) : super(key: key);
  var params;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static const platform = MethodChannel('samples.flutter.dev/battery');

  // Get battery level.
  String _batteryLevel = 'Unknown battery level.';

  Future<void> _getBatteryLevel() async {
    String batteryLevel;
    try {
      final int result = await platform.invokeMethod('getBatteryLevel');
      batteryLevel = 'Battery level at $result % .';
    } on PlatformException catch (e) {
      batteryLevel = "Failed to get battery level: '${e.message}'.";
    }

    setState(() {
      _batteryLevel = batteryLevel;
    });
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
            body: Container(
                child: Column(children: [
      ElevatedButton(
        child: Text('Get Battery Level'),
        onPressed: _getBatteryLevel,
      ),
      Text(_batteryLevel),
      Text("平台${Platform.isAndroid}"),
      Text("平台${Platform.operatingSystem}"),
      Text("我是原生页面传参ss==${widget.params}"),
    ]))));
  }
}

class MyHomepage2 extends StatefulWidget {
  const MyHomepage2({Key? key}) : super(key: key);

  @override
  _MyHomepage2State createState() => _MyHomepage2State();
}

class _MyHomepage2State extends State<MyHomepage2> {
  EventChannel _eventChannelPlugin = EventChannel("Event_Channel");
  late StreamSubscription? _streamSubscription;
  var msg;
  var logger = Logger();

  @override
  void initState() {
    _streamSubscription = _eventChannelPlugin
        //["abc", 123, "你好"]对应着Android端onListen方法的第一个参数，可不传值
        .receiveBroadcastStream(["abc", 123, "你好"]).listen(_onToDart,
            onError: _onToDartError, onDone: _onDone);
    super.initState();
  }

  @override
  void dispose() {
    if (_streamSubscription != null) {
      _streamSubscription!.cancel();
      _streamSubscription = null;
    }
    super.dispose();
  }

  //native端发送正常数据
  void _onToDart(message) {
    print(message);
    msg = message;
    logger.d("message=$message");
  }

  //当native出错时，发送的数据
  void _onToDartError(error) {
    print(error);
    logger.d("error=$error");
  }

  //当native发送数据完成时调用的方法，每一次发送完成就会调用
  void _onDone() {
    logger.d("消息传递完毕");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.green,
        child: Center(child: Text("msg==$msg")),
      ),
    );
  }
}

class HomePage3 extends StatefulWidget {
  const HomePage3({Key? key}) : super(key: key);

  @override
  _HomePage3State createState() => _HomePage3State();
}

class _HomePage3State extends State<HomePage3> {
  MethodChannel _methodChannel = MethodChannel("MethodChannelPlugin");

  // @override
  // void initState() {
  //   _methodChannel.setMethodCallHandler((handler) => Future<String>(() {
  //         print("_methodChannel：${handler}");
  //         //监听native发送的方法名及参数
  //         switch (handler.method) {
  //           case "send":
  //             _send(handler.arguments); //handler.arguments表示native传递的方法参数
  //             break;
  //         }
  //       }));
  //   super.initState();
  // }

  //native调用的flutter方法
  void _send(arg) {
    setState(() {});
  }

  String _resultContent = "";

  //flutter调用native的相应方法
  void _sendToNative() {
    // Future<String> future =
    //     _methodChannel.invokeMethod("send", _controller.text);
    // future.then((message) {
    //   setState(() {
    //     //message是native返回的数据
    //     _resultContent = "返回值：" + message;
    //   });
    // });
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

class Homepage4 extends StatefulWidget {
  const Homepage4({Key? key}) : super(key: key);

  @override
  _Homepage4State createState() => _Homepage4State();
}

class _Homepage4State extends State<Homepage4> {
  //StringCodec()为编码格式
  BasicMessageChannel<String> _basicMessageChannel =
      BasicMessageChannel("BasicMessageChannelPlugin", StringCodec());

  var _content;
  late TextEditingController _controller;

  @override
  void initState() {
    _basicMessageChannel.setMessageHandler((message) => Future<String>(() {
          print(message);
          //message为native传递的数据
          setState(() {
            _content = message;
          });
          //给Android端的返回值
          return "收到Native消息：" + message!;
        }));
    _controller = TextEditingController();
    super.initState();
  }

  //向native发送消息
  void _sendToNative() {
    Future<String?> future = _basicMessageChannel.send(_controller!.text);
    future.then((message) {
      print("返回值：" + message!);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

class BasicMessageChannelDemo extends StatefulWidget {
  @override
  _BasicMessageChannelDemoState createState() =>
      _BasicMessageChannelDemoState();
}

class _BasicMessageChannelDemoState extends State<BasicMessageChannelDemo> {
  var channel = BasicMessageChannel(
      'com.flutter.guide.BasicMessageChannel', StandardMessageCodec());

  var _data;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          SizedBox(
            height: 50,
          ),
          RaisedButton(
            child: Text('发送数据到原生'),
            onPressed: () async {
              var result = await channel.send({'name': 'laomeng', 'age': 18});
              result as Map<String, dynamic>;
              var name = result['name'];
              var age = result['age'];
              setState(() {
                _data = '$name,$age';
              });
            },
          ),
          Text('原生返回数据：$_data'),
        ],
      ),
    );
  }
}

class OnePage extends StatelessWidget {
  const OnePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.green,
    );
  }
}

class TwoPage extends StatelessWidget {
  var ss = window.defaultRouteName;

  String _getPageName(String s) {
    if (s.indexOf("?") == -1) {
      return s;
    } else {
      return s.substring(0, s.indexOf("?"));
    }
  }

  String _getPageParamJsonStr(String s) {
    if (s.indexOf("?") == -1) {
      return "{}";
    } else {
      return s.substring(s.indexOf("?") + 1);
    }
  }

  TwoPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          child: Text("我是原生页面传参ss==${_getPageParamJsonStr(ss)}"),
          color: Colors.red,
        ),
      ),
    );
  }
}
